package aop;

import com.google.common.collect.ImmutableMap;
import common.pojo.CommonResult;
import common.utils.JsonUtils;
import common.utils.MyMapUtils;
import handle.WebSocketPushHandler;
import httpclient.HttpClientUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import pojo.ChatRecord;
import pojo.MessageModel;
import pojo.UserShopInfo;
import pojo.WxUserInfo;
import pojo.form.ChatListAddForm;
import pojo.form.ChatRecordAddForm;
import service.ChatAopService;
import service.ChatListService;
import service.cfg.ShopCfg;
import service.cfg.WxUserCfg;
import unit.PushUnits;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by asus on 2018/11/22.
 */
@Aspect
@Component
public class ChatAop {
    @Autowired
    ChatAopService chatAopService;
    @Autowired
    ChatListService listService;
    @Autowired
    WxUserCfg wxUserCfg;
    @Autowired
    ShopCfg shopCfg;
    //店铺id
    private static final String SHOPID = "shopId";
    //wxUserId
    private static final String CUSTOMEID="customId";
    private final Logger LOG = LoggerFactory.getLogger(ChatAop.class);
    @AfterReturning(pointcut = "execution(* handle.WebSocketPushHandler.handleMessage(..))" ,returning="returnValue" )
    public void addChatRecord(JoinPoint point, Object returnValue){
       WebSocketSession session =(WebSocketSession) point.getArgs()[0];
       TextMessage message=(TextMessage)point.getArgs()[1];
        Long shopId = NumberUtils.toLong( session.getAttributes().get(SHOPID).toString());
        Long customId=NumberUtils.toLong( session.getAttributes().get(CUSTOMEID).toString());
        String isRead=session.getAttributes().get("isRead").toString();
        String isShop=session.getAttributes().get("isShop").toString();
        String isSend=session.getAttributes().get("isSend").toString();
        String msg=message.getPayload();
        MessageModel record = JsonUtils.JsonToPojo(msg, MessageModel.class);
        ChatRecordAddForm addForm = new ChatRecordAddForm(msg,record.getUrl(),isShop,shopId,new Date(),customId);
        chatAopService.addChatRecord(addForm);

        ChatListAddForm chatListAddForm = new ChatListAddForm();
        chatListAddForm.setCustomId(customId);
        chatListAddForm.setPhoto(record.getUrl());
        chatListAddForm.setShopId(shopId);

        CommonResult commonResult = HttpClientUtils.get(wxUserCfg.getWxUserInfo(), ImmutableMap.<String, Object>of("id", customId));
        WxUserInfo  userInfo = JsonUtils.objectToPojo(commonResult.getData(),WxUserInfo.class);
        if(userInfo==null){
            chatListAddForm.setNickName("默认");
        }else {
            chatListAddForm.setNickName(userInfo.getNickName());
        }

        if(isSend.equals("Y")){
            //推送模板消息
                HttpClientUtils.post(wxUserCfg.sendMsg(),ImmutableMap.of("customId",customId,"shopName",userInfo.getNickName(),"message",record.getMessage(),"shopId",shopId));
        }
        if (isShop.equals("Y")){
            return;
        }
        if(isRead.equals("N")){
            chatAopService.updateChatList(record.getMessage(),shopId,customId,chatListAddForm);
            CommonResult result = HttpClientUtils.get(shopCfg.getShopInfoDetail(), ImmutableMap.of("shopId",shopId));
            UserShopInfo shopInfo = JsonUtils.objectToPojo(result.getData(), UserShopInfo.class);
            if(shopInfo==null){
                LOG.warn("------消息推送失败--shopId----"+shopId);
                return;
            }
            Map map = new HashMap();
            map.put("bsId","qy_luozs");
            map.put("userId",shopInfo.getWxId());
            map.put("content",record.getMessage());
            if ( PushUnits.sendMsg(map).isNotSuccess()){
                LOG.warn("------消息推送失败--shopId----"+shopId+"--wxId---"+shopInfo.getWxId());
            }
        }
        chatAopService.addCharRecordExist(chatListAddForm);
    }
}
